package engine.operators.natural;

import its.util.RandomFactory;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import engine.Operator;
import engine.Population;
import engine.individuals.TrafficNetIndividual;

/**
 * Uniform crossover operator. Offsprings have equal probability of inheriting
 * gene from both of his parents.
 * 
 */
public class NaturalMeanCrossover<T extends TrafficNetIndividual<?>>
		implements Operator<T> {

	/**
	 * Creates a uniform crossover object.
	 */
	public NaturalMeanCrossover() {
	}

	/** {@inheritDoc} */
	@SuppressWarnings("unchecked")
	public Population<T> apply(Population<T> population) {
		List<T> individuals = population.getIndividuals();
		Collections.shuffle(individuals, RandomFactory.getRandom());

		Iterator<T> iterator = individuals.iterator();
		List<T> output = new ArrayList<T>(population.size());

		while (iterator.hasNext()) {
			T b1 = iterator.next();
			if (iterator.hasNext()) {
				T b2 = iterator.next();

				T[] crossedOver = (T[]) b1.crossOver(b2);

				output.add(crossedOver[0]);
				output.add(crossedOver[1]);
			} else {
				output.add(b1);
			}
		}

		return new Population<T>(output);
	}
}
